const service = require("../../../service/activity.js");
const serviceaddcar = require("../../../service/port.js")
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isNoData : false, //是否没有数据
    listitems: [],
    currentindex: 0,
    itemdata: [],
    pageNum: 1,
    pageSize: 10,
    noData: false,
    noDatas: false,
    currentDescription: {},
    chooseList: [],
    totalMoney: 0
  },
  formatDateTime(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second = date.getSeconds();
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
  },
  getList(callback) {
    var self = this;
    service.getSetMealList({
      'startTime': self.formatDateTime(new Date())
    }, res => {
      //console.log(res)

      self.setData({
        listitems: res.data,
        isNoData : res.data.length == 0
      })
      service.getSetMealSkuList({
        "setMealSku": {
          'setmealId': res.data[self.data.currentindex].setmealId
        },
        "queryRequest": {
          "pageNum": self.data.pageNum,
          "pageSize": self.data.pageSize
        }
      }, rest => {
        //console.log(rest)
        // for (let i = 0; i < rest.data.rows.length; i++) {
        //   const element = rest.data.rows[i];
        //   element.persent = (element.setmealTockNow / element.setmealTock) * 100 + '%';
        //   datas.push(element)
        // }
        // self.setData({
        //   itemdata: datas
        // })
        callback(rest);
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var self = this;
    const datas = [];
    // 订单列表
    wx.showLoading({
      title: "加载中...",
    });

    this.getList(function (res) {
      //console.log(res);
      self.setData({
        currentDescription: self.data.listitems[0],
        totalMoney:self.data.listitems[0].setmealMoney
      })
      for (let i = 0; i < res.data.rows.length; i++) {
        const element = res.data.rows[i];
        element.persent = (element.setmealTockNow / element.setmealTock) * 100 + '%';
        element.select = false;
        datas.push(element)
      }
      if (res.data.rows == 0) {
        self.setData({
          noDatas: true,
          noData: false
        });
      } else if (res.data.rows > 0 && res.data.rows < 4) {
        self.setData({
          noData: true,
        });
      }
      self.setData({
        itemdata: datas
      })
      wx.hideLoading();
    });

  },
  //添加购物车
  addcart(e) {
    console.log(e)
    // if (this.data.currentsku == '') {
    //   Toast.fail('请选择规格');
    //   return
    // }
    // if (this.data.currentInfo.stock == 0) {
    //   Toast.fail('该商品规格无库存！');
    //   return
    // }
    serviceaddcar.addcart({
      customerId: wx.getStorageSync('userInfo').id,
      spuId: e.currentTarget.dataset.index.spuId,
      skuId: e.currentTarget.dataset.index.skuId,
      num: 1
    }, res => {
      wx.showToast({
        title: '已加入购物车',
        icon: 'success',
        duration: 2000
      })
    })
  },
  scroll(e) {
    console.log(e)
  },

  scrollToTop() {
    this.setAction({
      scrollTop: 0
    })
  },
  selectorTo(e) {
    let current = e.currentTarget.dataset.index;
    this.setData({
      currentindex: current,
      pageNum : 1,
      noDatas: false,
      noData: false,
      currentDescription: e.currentTarget.dataset.item,
      chooseList: [],
      totalMoney:e.currentTarget.dataset.item.setmealMoney
    })

    var self = this;
    const datas = [];
    // 订单列表
    wx.showLoading({
      title: "加载中...",
    });
    this.getList(function (res) {
      //console.log(res)
      for (let i = 0; i < res.data.rows.length; i++) {
        const element = res.data.rows[i];
        element.persent = (element.setmealTockNow / element.setmealTock) * 100 + '%';
        element.select = false;
        datas.push(element)
      }
      if (res.data.rows.length == 0) {
        self.setData({
          noDatas: true,
          noData: false
        });
        //console.log(self.data.noDatas)
      } else if (res.data.rows.length > 0 && res.data.rows.length < 4) {
        self.setData({
          noData: true,
        });
      }
      self.setData({
        itemdata: datas
      })
      wx.hideLoading();
    });

  },
  goodurlTo(e) {
    // console.log(e)
    let goodId = e.currentTarget.dataset.index.spuId
    wx.navigateTo({
      url: "/pages/product/productDetail/index?id=" + goodId + "&type=pack"

    });
  },
  selectGood(e) {
    const index = e.currentTarget.dataset.index;
    var objString = JSON.stringify(this.data.itemdata);
    var cartArray = JSON.parse(objString);
    cartArray[index].select = !cartArray[index].select;
    if (this.data.chooseList.length >= this.data.currentDescription.setmealNum && cartArray[index].select) {
      Toast.fail('最多可选' + this.data.currentDescription.setmealNum + "种商品！");
    } else {
      // 设置选中或不选中状态

      this.setData({
        itemdata: cartArray
      })
      var chooseList = [];
      
      for (let i = 0; i < cartArray.length; i++) {
        const element = cartArray[i];
        if (element.select) {
          chooseList.push(element);
          
        }
        this.setData({
          chooseList: chooseList,
          
        })
      }

    }






  },
  goconfirmOrder() {
    //console.log(this.data.chooseList);
    if (this.data.chooseList.length == 0) {
      Toast.fail('请选择商品！');
    } else if (this.data.chooseList.length < this.data.currentDescription.setmealNum || this.data.chooseList.length > this.data.currentDescription.setmealNum) {
      Toast.fail('必须选择' + this.data.currentDescription.setmealNum + '个商品！');
    } else {
      // console.log('选择的商品',this.data.chooseList)
      // const accountInfo = {
      //   isActivity: true,
      //   shoppingList: this.data.chooseList,
      //   totalMoney: this.data.totalMoney / 100,
      //   isfixedprice:true
      // }
      // wx.navigateTo({
      //   url: '/pages/order/createOrder/index?accountInfo=' + JSON.stringify(accountInfo),
      //   // url: '/pages/activity/confirmOrder/index?accountInfo=' + JSON.stringify(accountInfo),
      // })

      this.toFinalConfirmOrder()

    }
  },

  toFinalConfirmOrder () {
    let list = this.data.listitems
    let index = this.data.currentindex
    let orderInfo = {
      type: '3',
      shoppingList: this.data.chooseList,
      totalMoney: this.data.totalMoney,
      promotiomIds : list[index].setmealId,
    }
    console.log('orderInfo===========')
    console.log('打包一口价',orderInfo)
    console.log('orderInfo===========')
    orderInfo = JSON.stringify(orderInfo)
    wx.navigateTo({
      url: `/pages/order/finalComfirmOrder/index?orderInfo=${orderInfo}`,
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const datas = [];
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    this.setData({
      pageNum: 1,
      noData: false,
    });
    const self = this;
    this.getList(function (res) {
      for (let i = 0; i < res.data.rows.length; i++) {
        const element = res.data.rows[i];
        element.persent = (element.setmealTockNow / element.setmealTock) * 100 + '%';
        element.select = false;
        datas.push(element)
      }
      if (res.data.rows.length > 0 && res.data.rows.length < 4) {
        self.setData({
          itemdata: datas,
          noData: true,
        });
      } else {
        self.setData({
          itemdata: datas,
        });
      }
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 判读数据是否加载完毕
    if (this.data.noData) return;
    // 停止下拉刷新
    wx.stopPullDownRefresh();
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    const itemdata = this.data.itemdata;
    let pageNum = this.data.pageNum;
    this.setData({
      // 每次下拉 page+1
      pageNum: ++pageNum,
    });
    const self = this;
    self.getList(function (res) {
      if (res.data.rows.length == 0) {
        self.setData({
          noData: true,
        });
      } else {
        res.data.rows.forEach((item) => {
          item.select = false;
          itemdata.push(item);
        });
        self.setData({
          itemdata: itemdata,
        });
      }
    });
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})